<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" 
      v-model="person.name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" 
      v-model="person.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="person.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add(person)">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item , index) in arr"
        :key="index">
          <td>{{index + 1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      arr:[
        {
          id:1,
          name:'小亮',
          age: 23,
          gender:'男'
        },
        {
          id:2,
          name:'小海',
          age: 22,
          gender:'男'
        },
        {
          id:3,
          name:'小汪',
          age: 21,
          gender:'男'
        },
      ],
      person :{
        name:'',
        age:'',
        gender:''
      },
      // 定义全局开关变量
      flag:true
    }
  },
  methods:{
   add(person){
      if(this.flag){
          // 非空判断
          for(let k in this.person){
            if(!this.person[k]) return alert('请输入内容')
            // console.log(this.person[k]);
          }
          this.arr.push({
            id:this.arr[this.arr.length - 1].id + 1 || 1 ,
            name:this.person.name,
            age:this.person.age,
            gender:this.person.gender
          })
      } else {
        const index = this.arr.findIndex(item => item.id === person.id)
        this.arr.splice(index,1,{
          name:this.person.name,
          age:this.person.age,
          gender:this.person.gender
        })
        // 改变 flag 状态
      this.flag = true
      }
       this.person.name = ''
      this.person.age = ''
      this.person.gender = ''
      
   },
   edit(id){
    const obj = this.arr.find(item => item.id === id)
    this.person.name = obj.name
    this.person.age = obj.age
    this.person.gender = obj.gender
    // 改变flag 状态
    this.flag = false
   },
   del(id){
    const index = this.arr.findIndex(item => item.id === id ) 
    this.arr.splice(index , 1)
   }
  }
}
</script>